const express = require('express');
const { ObjectId } = require('mongodb');
const router = express.Router();
const Announcement = require('../models/Announcement');

const errorRes = (res, msg, code = 400) => res.status(code).json({ code, msg });

// 获取公告列表
router.get('/list', async (req, res) => {
  try {
    let { page, size } = req.query;
    page = parseInt(page) || 1;
    size = parseInt(size) || 10;

    const data = await Announcement.find().skip((page - 1) * size).limit(size);
    const total = await Announcement.countDocuments();

    res.json({ code: 200, data, total });
  } catch (error) {
    errorRes(res, '获取公告列表失败', 500);
  }
});

// 添加公告
router.post('/add', async (req, res) => {
  try {
    const { title, content } = req.body;
    if (!title || !content) return errorRes(res, '标题和内容不能为空');

    const newAnnouncement = await Announcement.create(req.body);

    // Socket.IO 推送新公告通知
    const io = req.app.get('io');
    if (io) {
      io.emit('newAnnouncement', {
        announcement: newAnnouncement,
        message: '有新的公告发布，请查看！'
      });
    }

    res.json({ code: 200, msg: '添加成功' });
  } catch (error) {
    errorRes(res, '添加公告失败', 500);
  }
});

// 更新公告
router.post('/up', async (req, res) => {
  try {
    const { _id, title, content } = req.body;
    if (!_id) return errorRes(res, '缺少公告ID');
    if (!ObjectId.isValid(_id)) return errorRes(res, '无效的公告ID格式');
    if (!title || !content) return errorRes(res, '标题和内容不能为空');

    const result = await Announcement.updateOne({ _id: new ObjectId(_id) }, req.body);
    if (result.matchedCount === 0) return errorRes(res, '公告不存在', 404);

    res.json({ code: 200, msg: '更新成功' });
  } catch (error) {
    errorRes(res, '更新公告失败', 500);
  }
});

// 删除公告
router.post('/del', async (req, res) => {
  try {
    const { _id } = req.body;
    if (!_id) return errorRes(res, '缺少公告ID');
    if (!ObjectId.isValid(_id)) return errorRes(res, '无效的公告ID格式');

    const result = await Announcement.deleteOne({ _id: new ObjectId(_id) });
    if (result.deletedCount === 0) return errorRes(res, '公告不存在', 404);

    res.json({ code: 200, msg: '删除成功' });
  } catch (error) {
    errorRes(res, '删除公告失败', 500);
  }
});

module.exports = router;